package com.pipe.service.impl;

import cn.hutool.core.util.IdUtil;
import com.google.gson.Gson;
import com.pipe.config.OSSProperties;
import com.pipe.service.OssService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @ClassName OssServiceImpl
 * @Author HETAO
 * @Date 2020/7/9 20:32
 */
public class QiNiuOssServiceImpl implements OssService {

    private static final Logger log = LoggerFactory.getLogger(QiNiuOssServiceImpl.class);

    private OSSProperties prop;

    public QiNiuOssServiceImpl(OSSProperties prop) {
        this.prop = prop;
    }

    @Override
    public String uploadByOss(MultipartFile file) {
        Auth auth = Auth.create(prop.getAccessKey(), prop.getSecretKey());
        String upToken = auth.uploadToken(prop.getBucketName());
        Configuration cfg = new Configuration(Region.region0());
        UploadManager uploadManager = new UploadManager(cfg);
        String fileName = null;
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
            //日期格式化
            String date = LocalDateTime.now().format(formatter);
            //添加uuid
            fileName = date+"/"+ IdUtil.simpleUUID() + file.getOriginalFilename();
            Response response = uploadManager.put(file.getInputStream(), fileName, upToken,null,null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            log.info("{}产商,上传成功:{}",prop.getOssSelect(),putRet.key);
            return fileName;
        } catch (QiniuException ex) {
            Response r = ex.response;
            log.error("七牛云:文件上传失败：",r.toString());
            try {
                log.error("响应体:",r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 字节数组上传
     * @param uploadBytes
     * @param key
     */
    public String uploadByOss(byte[] uploadBytes,String key) {
        Configuration cfg = new Configuration(Region.region0());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(prop.getAccessKey(), prop.getSecretKey());
        String upToken = auth.uploadToken(prop.getBucketName());
        try {
            Response response = uploadManager.put(uploadBytes, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            log.info("{}产商,上传成功:{}",prop.getOssSelect(),putRet.key);
            return putRet.key;
        } catch (QiniuException ex){
            Response r = ex.response;
            log.error("七牛云:文件上传失败：",r.toString());
            try {
                log.error("响应体:",r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return null;
    }

    /**
     * 流的形式
     * @param file
     * @param key
     */
    public String uploadByInputStream(String file,String key) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        UploadManager uploadManager = new UploadManager(cfg);
        try {
            byte[] uploadBytes = file.getBytes("utf-8");
            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(prop.getAccessKey(), prop.getSecretKey());
            String upToken = auth.uploadToken(prop.getBucketName());
            try {
                Response response = uploadManager.put(byteInputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                log.info("{}产商,上传成功:{}",prop.getOssSelect(),putRet.key);
                return putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                log.error("七牛云:文件上传失败：",r.toString());
                try {
                    log.error("响应体:",r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (UnsupportedEncodingException ex) {
            //ignore
        }
        return null;
    }

    /**
     * 断点续上传
     * @param path
     * @param key
     */
    public String continueUploading  (String path,String key) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        Auth auth = Auth.create(prop.getAccessKey(), prop.getSecretKey());
        String upToken = auth.uploadToken(prop.getBucketName());
        String localTempDir = Paths.get(System.getenv("java.io.tmpdir"), prop.getBucketName()).toString();
        try {
            //设置断点续传文件进度保存目录
            FileRecorder fileRecorder = new FileRecorder(localTempDir);
            UploadManager uploadManager = new UploadManager(cfg, fileRecorder);
            try {
                Response response = uploadManager.put(path, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                log.info("{}产商,上传成功:{}",prop.getOssSelect(),putRet.key);
                return putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                log.error("七牛云:文件上传失败：",r.toString());
                try {
                    log.error("响应体:",r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
